<?php

/**
 * This is the model class for table "{{customer}}".
 *
 * The followings are the available columns in table '{{customer}}':
 * @property integer $id
 * @property integer $user_id
 * @property string $ckey
 * @property string $status
 * @property string $firstname
 * @property string $lastname
 * @property string $address
 * @property string $address2
 * @property integer $gender
 * @property integer $birthday
 * @property string $city
 * @property string $country
 * @property string $postal_code
 * @property string $home_phone
 * @property string $mobile_phone
 * @property string $office_phone
 * @property integer $biz_id
 * @property integer $staff_id
 */
class Customer extends CActiveRecord
{

    const STATUS_ACTIVE = 'active';
    const STATUS_BLOCK  = 'block';
    const GENDER_MALE   = 'M';
    const GENDER_FEMALE = 'F';

    public $email;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Customer the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @uses at validate rules()
     * @return mixed
     */
    public function get_arr_status()
    {
        return array(
            self::STATUS_ACTIVE,
            self::STATUS_BLOCK
        );
    }

    /**
     * use at validate
     * @return type
     */
    public function get_arr_gender()
    {
        return array(
            self::GENDER_FEMALE,
            self::GENDER_MALE,
        );
    }

    /**
     * 
     * @param type $email
     * @param type $merchant_ukey
     * @return boolean <b>TRUE</b> if email is first time with merchant, <b>FALSE</b> if otherwise
     */
    public static function check_is_first_time($email, $merchant_ukey)
    {

        //find user in db
        $user = Users::model()->findByAttributes(array('email' => $email));

        if (NULL == $user)
        {
            return TRUE;
        }
        else
        {

            //find all record in tbl_customer
            $list_customer = $user->customers;


            //if has no record, it meaning that this customer have not book any service yet
            if (NULL == $list_customer OR FALSE == $list_customer)
            {
                return TRUE;
            }

            $list_id_of_merchant = Users::get_id_all_branch($merchant_ukey);
            $id_customer         = $user->id;

            foreach ($list_id_of_merchant as $m)
            {

                if (Customer::checkCustomerBelongToBiz($id_customer, $m))
                {

                    return FALSE;
                    break;
                }
            }

            return TRUE;
        }
    }

    public static function is_1st_with_current_user($merchant_ukey)
    {

        if (Yii::app()->user->isGuest)
        {
            return FALSE;
        }

        $merchant = Users::model()->findByAttributes(array('ukey' => $merchant_ukey));

        if (NULL == $merchant)
        {
            return FALSE;
        }
        else
        {

            //if this merchant is a branch
            if ($merchant->getIsBranch())
            {

                if (self::checkCustomerBelongToBiz(Yii::app()->user->id, $merchant->id))
                    return FALSE;

                $parent = Users::model()->findByPk($merchant->author_id);

                if (NULL == $parent)
                {
                    return FALSE;
                }
                else
                {

                    if (self::checkCustomerBelongToBiz(Yii::app()->user->id, $parent->id))
                        return FALSE;

                    $list_branch = $parent->get_my_branch();
                    //if have not branch
                    if (FALSE == $list_branch)
                    {
                        return !self::checkCustomerBelongToBiz(Yii::app()->user->id, $parent->id);
                    }
                    else
                    {
                        foreach ($list_branch as $m)
                        {

                            //if is customer of merchant
                            if (self::checkCustomerBelongToBiz(Yii::app()->user->id, $m->id))
                            {
                                return FALSE;
                                break;
                            }
                        }
                    }
                }
            }
            else
            {

                if (self::checkCustomerBelongToBiz(Yii::app()->user->id, $merchant->id))
                    return FALSE;


                $list_branch = $merchant->get_my_branch();

                //if have not branch
                if (FALSE == $list_branch)
                {
                    return !self::checkCustomerBelongToBiz(Yii::app()->user->id, $merchant->id);
                }
                else
                {


                    foreach ($list_branch as $m)
                    {

                        //if is customer of merchant
                        if (self::checkCustomerBelongToBiz(Yii::app()->user->id, $m->id))
                        {
                            return FALSE;
                            break;
                        }
                    }
                }
            }
        }

        return TRUE;
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{customer}}';
    }

    /**
     * 
     * @param type $user_id
     * @param type $biz_id
     * @return boolean <b>FALSE</b> if check false or <b>a signle active record</b> otherwise
     */
    public static function checkCustomerBelongToBiz($user_id, $biz_id)
    {
        $record = Customer::model()->find('user_id=:user_id AND biz_id=:biz_id', array(
            ':biz_id' => $biz_id,
            'user_id' => $user_id
        ));

        if ($record != NULL)
        {
            return $record;
        }
        else
        {
            return FALSE;
        }
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            //array('firstname, lastname', 'required'),
            array('user_id, biz_id, staff_id', 'numerical', 'integerOnly' => true),
            array('email', 'email', 'on' => 'create_backend'),
            array('email', 'required', 'on' => 'create_backend'),
            array('email', 'check_allow', 'on' => 'create_backend'),
            //setting in list
            array('status', 'in', 'range' => $this->get_arr_status(), 'allowEmpty' => false, 'on' => 'create_backend'),
            array('gender', 'in', 'range' => $this->get_arr_gender(), 'allowEmpty' => false, 'on' => 'create_backend'),
            array('country', 'in', 'range' => Country::get_arr_country(), 'allowEmpty' => false, 'on' => 'create_backend'),
            array('ckey, country', 'length', 'max' => 50),
            array('firstname, lastname', 'length', 'max' => 128),
            array('address,address2', 'length', 'max' => 255),
            array('city, home_phone, mobile_phone, office_phone', 'length', 'max' => 30),
            array('postal_code, status', 'length', 'max' => 20),
            array('gender, status, birthday, firstname, lastname, address, city, country, home_phone', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, user_id, ckey, status, firstname, lastname, address, gender, birthday, city, country, postal_code, home_phone, mobile_phone, office_phone, biz_id, staff_id', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        $relations         = parent::relations();
        $relations['user'] = array(
            self::BELONGS_TO, 'Users', 'user_id',
        );

        $relations['biz']    = array(
            self::BELONGS_TO, 'Users', 'biz_id',
        );
        $relations['aptcus'] = array(
            self::HAS_MANY, 'AptCustomer', 'customer_id',
        );

        return $relations;
    }

    public function check_allow($attribute, $params)
    {

        if (Yii::app()->user->isAdmin())
        {

            if ($this->isNewRecord)
            {
                //find customer in db
                $cuser = Users::check_exist_by_email($this->email, Users::TYPE_CUSTOMER);

                if ($cuser)
                {
                    if (isset($_POST['Customer']['biz_id']))
                        $cus_biz = $this->checkCustomerBelongToBiz($cuser->id, $_POST['Customer']['biz_id']);
                    else
                        $cus_biz = $this->checkCustomerBelongToBiz($cuser->id, $_POST['Users']['biz_id']);

                    //if customer belong to the merchant
                    if ($cus_biz)
                    {
                        $this->addError($attribute, Yii::t('main', 'This email has been customer of the merchant'));
                        return;
                    }
                }
            }
        }

        if (Yii::app()->user->isMerchant())
        {
            if ($this->isNewRecord)
            {
                //find customer in db
                $cuser = Users::check_exist_by_email($this->email, Users::TYPE_CUSTOMER);

                if ($cuser)
                {

                    $cus_biz = $this->checkCustomerBelongToBiz($cuser->id, Yii::app()->user->getId());

                    //if customer belong to the merchant
                    if ($cus_biz)
                    {
                        $this->addError($attribute, Yii::t('main', 'This email has been customer of the merchant'));
                        return;
                    }
                }
            }
        }

        if (Yii::app()->user->isStaff())
        {
            if ($this->isNewRecord)
            {
                //find customer in db
                $cuser = Users::check_exist_by_email($this->email, Users::TYPE_CUSTOMER);

                if ($cuser)
                {
                    $biz_merchant = Users::getMyBiz(Yii::app()->user->getId());

                    if (!$biz_merchant)
                    {
                        $this->addError($attribute, Yii::t('main', 'Not found the merchant'));
                        return;
                    }

                    $cus_biz = $this->checkCustomerBelongToBiz($cuser->id, $biz_merchant);

                    //if customer belong to the merchant
                    if ($cus_biz)
                    {
                        $this->addError($attribute, Yii::t('main', 'This email has been customer of the merchant'));
                        return;
                    }
                }
            }
        }
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id'           => 'ID',
            'user_id'      => Yii::t('main', 'User'),
            'ckey'         => Yii::t('main', 'Customer key'),
            'firstname'    => Yii::t('main', 'Firstname'),
            'lastname'     => Yii::t('main', 'Lastname'),
            'status'       => Yii::t('main', 'Status'),
            'address'      => Yii::t('main', 'Address'),
            'address2'     => Yii::t('main', 'Address2'),
            'gender'       => Yii::t('main', 'Gender'),
            'birthday'     => Yii::t('main', 'Birthday'),
            'city'         => Yii::t('main', 'Area'),
            'postal_code'  => Yii::t('main', 'Postal Code'),
            'home_phone'   => Yii::t('main', 'Home Phone'),
            'mobile_phone' => Yii::t('main', 'Mobile Phone'),
            'office_phone' => Yii::t('main', 'Office Phone'),
            'biz_id'       => Yii::t('main', 'Merchant'),
            'staff_id'     => Yii::t('main', 'Staff'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('user_id', $this->user_id);
        $criteria->compare('ckey', $this->ckey, true);
        $criteria->compare('firstname', $this->firstname, true);
        $criteria->compare('lastname', $this->lastname, true);
        $criteria->compare('status', $this->status, true);
        $criteria->compare('address', $this->address, true);
        $criteria->compare('address2', $this->address2, true);
        $criteria->compare('gender', $this->gender);
        $criteria->compare('birthday', $this->birthday);
        $criteria->compare('city', $this->city, true);
        $criteria->compare('postal_code', $this->postal_code, true);
        $criteria->compare('home_phone', $this->home_phone, true);
        $criteria->compare('mobile_phone', $this->mobile_phone, true);
        $criteria->compare('office_phone', $this->office_phone, true);
        $criteria->compare('biz_id', $this->biz_id);
        $criteria->compare('staff_id', $this->staff_id);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public static function getArrayStatus()
    {
        return array(
            self::STATUS_ACTIVE => Yii::t('main', 'Active'),
            self::STATUS_BLOCK  => Yii::t('main', 'Block'),
        );
    }

    public function getMerchatName()
    {
        if ($this->biz == NULL)
        {
            return "<span class='label label-important'>webmaster</span>";
        }
        else
        {
            return "<span class='label label-success'>" . $this->biz->name . "</span>";
        }
    }

    public function getStatusLabel()
    {
        if (!$this->hasAttribute("status"))
            return '';

        $labelClass = 'label ';
        switch ($this->status)
        {
            case self::STATUS_ACTIVE:
                $labelClass .= 'label-success';
                break;

            case self::STATUS_BLOCK:
                $labelClass .= 'label-important';
                break;

            default:
                break;
        }
        $labels = self::getArrayStatus();
        $label  = isset($labels[$this->status]) ? $labels[$this->status] : $this->status;
        return "<span class='$labelClass'>$label</span>";
    }

    static function getIdByCkey($ckey)
    {
        $customer = self::model()->find('ckey=:c', array(
            ':c' => $ckey,
        ));

        if ($customer != NULL)
            return $customer->id;
        else
            return NULL;
    }

    public function getFullAddress()
    {
        $location = $this->address . ' ' . $this->city . ' ' . $this->postal_code;
        if (trim($location) != '')
        {
            return $location;
        }
        else
        {
            return $this->getAddressCustomerBelongUser();
        }
    }

    public function getPhoneAndType()
    {
        if ($this->mobile_phone != NULL)
            return Users::MOBILE;
        if ($this->home_phone != NULL)
            return Users::HOME_PHONE;
        if ($this->office_phone != NULL)
            return Users::OFFICE_PHONE;
    }

    public function getMail()
    {
        $user = Users::model()->findByPk($this->user_id);
        if ($user == Null)
        {
            return '';
        }
        else
        {
            return $user->email;
        }
    }

    public function getEmail()
    {
        if ($this->user == null)
        {
            return null;
        }

        return $this->user->email;
    }

    public function getStatus()
    {
        if ($this->user == null)
        {
            return null;
        }

        return $this->user->status;
    }

    /**
     * 
     */
    function get_all_notes()
    {

        $criteria = new CDbCriteria();


        if (Yii::app()->user->isAdmin() OR Yii::app()->user->isConcierge())
        {
            
        }
        else
        {
            $list_id_branh = Users::get_all_branch_id_of_user_logedin();
            $criteria->addInCondition('customer.biz_id', $list_id_branh);
            $criteria->addInCondition('t.author', $list_id_branh);
        }
        $criteria->addCondition('customer.user_id=' . $this->user_id);
        $criteria->with  = array('customer');
        $criteria->order = 't.date DESC';
        $criteria->limit = 50;

        $notes = CustomerNote::model()->findAll($criteria);

        if ($notes == NULL)
        {
            return array();
        }
        else
        {
            $arr = array();
            foreach ($notes as $v)
            {
                $arr[] = array(
                    'date' => date('D, d M, Y', $v->date),
                    'note' => $v->note_content
                );
            }
            return $arr;
        }
    }

    /**
     * use at AppointmentController.php     
     */
    public function getNote()
    {

        $criteria            = new CDbCriteria();
        $criteria->order     = 'date DESC';
        $criteria->condition = 'customer_id=:cus_id';
        $criteria->params    = array(':cus_id' => $this->id);

        $note = CustomerNote::model()->findAll($criteria);

        if ($note == NULL)
        {
            return array();
        }
        else
        {
            $arr = array();
            foreach ($note as $v)
            {
                $arr[] = array(
                    'date' => date('D, d M, Y', $v->date),
                    'note' => $v->note_content
                );
            }
            return $arr;
        }
    }

    public function getPhone()
    {
        if ($this->user)
        {
            if ($this->user->mobile_phone != NULL)
                return $this->user->mobile_phone;
            if ($this->user->home_phone != NULL)
                return $this->user->home_phone;
            if ($this->user->office_phone != NULL)
                return $this->user->office_phone;
        }
        return '';
    }

    /**
     * @return List of Appointment  that user belong to
     */
    public function getListAppoint()
    {

        $criteria = new CDbCriteria();

        //if admin or concerige role, show all appoinmnet
        if (Yii::app()->user->isAdmin())
        {
            $criteria->with = array('customer');
            $criteria->compare('customer.user_id', $this->user_id);
        }

        //if branch, only show its appoinmnet
        if (Yii::app()->user->isBranch())
        {
            $criteria->with = array('customer');
            $criteria->compare('customer.biz_id', Yii::app()->user->id);
            $criteria->compare('customer.user_id', $this->user_id);
        }

        //if merchant, show all 
        if (Yii::app()->user->isMerchant())
        {
            $criteria->with = array('customer');
            $criteria->compare('customer.user_id', $this->user_id);

            $list_id_branh = Users::get_all_branch_id_of_user_logedin();

            $criteria->addInCondition('customer.biz_id', $list_id_branh);
        }

        if (Yii::app()->user->isStaff())
        {
            $curr_user = Yii::app()->user->getCurrentUser();

            $id_merchant = $curr_user->author_id;

            $criteria->with = array('customer');
            $criteria->compare('customer.user_id', $this->user_id);
            $criteria->compare('customer.biz_id', $id_merchant);
        }

        $criteria->order = 'apt_id DESC';

        $list = AptCustomer::model()->findAll($criteria);

        if ($list == NULL)
        {
            return array();
        }
        else
        {
            $arr = array();
            foreach ($list as $v)
            {
                if ($v->appt != NULL)
                {
                    $arr[] = array(
                        'id_appoint'   => $v->apt_id,
                        'service_name' => $v->appt->service->s_name,
                        'date'         => date('D M d Y', $v->appt->date),
                        'start_time'   => $v->appt->start_time,
                        'appoint_new'  => $v->appt->isProcess,
                    );
                }
            }
            return $arr;
        }
    }

    public function get_public_photo_by_size($w, $h)
    {
        if ($this->isNewRecord)
        {
            return Yii::app()->controller->assetDir . '/img/avatar-blank.jpg';
        }
        else
        {
            if (!$this->user)
            {
                return Yii::app()->controller->assetDir . '/img/avatar-blank.jpg';
            }
            if ($this->user->photo)
            {
                if (strpos($this->user->photo, 'http') !== FALSE)
                {
                    return $this->user->photo;
                }
                else
                {
                    return $this->user->getAvartBySize($w, $h);
                }
            }
            else
            {
                return Yii::app()->controller->assetDir . '/img/avatar-blank.jpg';
            }
        }
    }

    public function getPublicPhoto()
    {
        if ($this->isNewRecord)
        {
            return Yii::app()->controller->assetDir . '/img/avatar-blank.jpg';
        }
        else
        {
            if (!$this->user)
            {
                return Yii::app()->controller->assetDir . '/img/avatar-blank.jpg';
            }
            if ($this->user->photo)
            {
                if (strpos($this->user->photo, 'http') !== FALSE)
                {
                    return $this->user->photo;
                }
                else
                {
                    return $this->user->publicPhoto;
                }
            }
            else
            {
                return Yii::app()->controller->assetDir . '/img/avatar-blank.jpg';
            }
        }
    }

    public static function getCreateUrl($type)
    {
        return Yii::app()->createUrl("customer/create");
    }

    public static function getImportUrl($type)
    {
        return Yii::app()->createUrl("customer/import");
    }

    public function getViewUrl()
    {
        return Yii::app()->createUrl("customer/view", array(
                    "pk" => $this->ckey,
        ));
    }

    public function getEditUrl()
    {
        return Yii::app()->createUrl("customer/edit", array(
                    "pk" => $this->ckey,
        ));
    }

    public function getPackageUrl()
    {
        return Yii::app()->createUrl("customer/package", array(
                    "pk" => $this->ckey,
        ));
    }

    public function getDeleteUrl()
    {
        return Yii::app()->createUrl("customer/delete", array(
                    "pk" => $this->ckey,
        ));
    }

    public function getChangePassUrl()
    {
        return Yii::app()->createUrl('profile/changePassword');
    }

    public function getChangeEmailUrl()
    {
        return Yii::app()->createUrl('profile/changeEmail');
    }

    public function getName()
    {
        if ($this->user)
            return "{$this->user->firstname} {$this->user->lastname}";
        return '';
    }

    public static function getCkeybyId($id)
    {
        $crite         = new CDbCriteria();
        $crite->compare('id', $id);
        $crite->select = array('ckey', 'id');

        $cus = Customer::model()->find($crite);
        if ($cus == NULL)
        {
            return FALSE;
        }

        return $cus->ckey;
    }

    function genCkey()
    {
        // Prefix của ckey
        $prefix = Users::PREFIX_CUSTOMER;

        // Chuỗi số của ckey
        $result = crc32($this->id);
        if ($result < 0)
        {
            $result = '0' . abs($result);
        }
        $ukey = trim(sprintf("%012d", $result));

        return "$prefix-$ukey";
    }

    function updateCkey()
    {
        $this->ckey = $this->genCkey();
        $this->update(array('ckey'));
    }

    /**
     * Retrieves a model
     * @param string $ckey ckey of customer
     * @return CActiveData 
     */
    public static function getRecordByCkey($ckey)
    {
        return self::model()->find('ckey=:ckey', array(':ckey' => $ckey));
    }

    public static function getRecordById($id)
    {
        return self::model()->findByPk($id);
    }

    public static function countCustomer()
    {
        $current_user = Users::getCurrentUser();

        $cri            = new CDbCriteria();
        $cri->condition = 'status=:st';

        if ($current_user->type == Users::TYPE_BUSINESS)
        {
            $cri->addCondition('biz_id=' . Yii::app()->user->getId());
        }
        elseif ($current_user->type == Users::TYPE_STAFF)
        {
            $idbiz = Users::getMyBiz(Yii::app()->user->getId());
            $cri->addCondition($idbiz);
        }


        $cri->params = array(
            ':st' => Users::STATUS_ACTIVE,
        );
        return self::model()->count($cri);
    }

    public function getPublicImage140()
    {
        $file       = Yii::getPathOfAlias('webroot') . '/' . $this->photo;
        list($w) = getimagesize($file);
        $percent    = round(140 / $w * 100);
        $dir_name   = dirname($file);
        $path_parts = pathinfo($file);
        $file_name  = $path_parts['filename'] . "'_163.jpg'";
        $thumb      = Yii::app()->phpThumb->create($file);
        $thumb->resizePercent($percent);
        $thumb->save($dir_name . '/' . $file_name);
        return Yii::app()->baseUrl . '/files/user' . '/' . $file_name;
    }

    public function getBirthday()
    {
        if ($this->user)
        {
            if (!empty($this->user->birthday))
                return date('d/M/Y', $this->birthday);
        }
        return '';
    }

    public function getCreateRetailOrderUrl()
    {
        return Yii::app()->createUrl('retailOrder/create', array(
                    'ckey' => $this->ckey
        ));
    }

    public function getAvartBySize($width, $height)
    {
        if (!$this->user)
        {
            return Yii::app()->controller->assetDir . '/img/avatar-blank.jpg';
        }
        if (!$this->user->photo)
        {
            return Yii::app()->controller->assetDir . '/img/avatar-blank.jpg';
        }

        $file = Yii::getPathOfAlias('webroot') . '/' . $this->user->photo;
        $path = Yii::getPathOfAlias('webroot') . '/files/user/';

        if (!file_exists($file))
        {
            return Yii::app()->controller->assetDir . '/img/avatar-blank.jpg';
        }

        $path_parts = pathinfo($file);

        $extesion  = $path_parts['extension'];
        $file_name = $path_parts['filename'] . "_w" . $width . 'h' . $height . '.' . $extesion;

        if (!file_exists($file_name) AND ! is_file($file_name))
        {
            $thumb = Yii::app()->phpThumb->create($file);
            $thumb->adaptiveResize($width, $height);
            $thumb->save($path . '/' . $file_name);
        }

        return Yii::app()->baseUrl . '/files/user' . '/' . $file_name;
    }

    public function getTotalSpent()
    {
//        if (Yii::app()->user->isAdmin())
//        {
        $orders_sql = "(select distinct order_id from `tbl_orders` where cus_ckey='$this->ckey')";
        $query      = "select sum(CAST(final_price as DECIMAL(4,2))) as total from `tbl_receipt` join `tbl_orders` on tbl_orders.order_id=tbl_receipt.order_id where tbl_orders.order_id IN $orders_sql";
        $cm         = Yii::app()->db->createCommand($query)->queryAll();
        $total      = empty($cm[0]['total']) ? 0 : $cm[0]['total'];
//        }
//        if (Yii::app()->user->isMerchant())
//        {
//            $orders_via_sp_sql = "(select distinct order_id from `tbl_orders` where cus_ckey='$this->ckey' and payment_via_webmaster=1)";
//            $orders_notvia_sp_sql = "(select distinct order_id from `tbl_orders` where cus_ckey='$this->ckey' and payment_via_webmaster=0)";
////            //compare with status payment by webmaster or not
//            $query_via = "(select sum(CAST(final_price as DECIMAL(4,2))) as total from `tbl_receipt` join `tbl_orders` on tbl_orders.order_id=tbl_receipt.order_id where tbl_orders.order_id IN $orders_via_sp_sql) AS total_via";
//            $query_notvia = "(select sum(CAST(final_price as DECIMAL(4,2))) as total from `tbl_receipt` join `tbl_orders` on tbl_orders.order_id=tbl_receipt.order_id where tbl_orders.order_id IN $orders_notvia_sp_sql) AS total_not_via";
//            $cm = Yii::app()->db->createCommand("select sum(total_via+total_not_via)")->queryAll();
//            $_total = empty($cm[0]['total']) ? 0 : $cm[0]['total'];
//            $total = (float) $_total * 0.7;
//        }
//        if (Yii::app()->user->isMerchant())
//            $total = (float) $total * 0.7;
        return number_format($total, 2, ".", ",");
    }

    /**
     * @param string $email customer email need to check
     * @param integer $merchant_id
     * @return boolean
     */
    public static function email_is_firsttime_with_merchant($email, $merchant_id)
    {
        $user_record = Users::model()->find('LOWER(email)=:email AND type=:t', array(
            ':email' => strtolower($email),
            ':t'     => Users::TYPE_CUSTOMER
        ));
        if ($user_record != NULL)
        {
            $list_id_of_merchant = Users::get_id_all_branch($merchant_id, TRUE);
            $id_customer         = $user_record->id;
            foreach ($list_id_of_merchant as $m_id)
            {
                if (Customer::checkCustomerBelongToBiz($id_customer, $m_id))
                {
                    return FALSE;
                    break;
                }
            }
        }
        return TRUE;
    }

}
